package com.liang.gulimall.auth.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.liang.common.constant.AuthServerConstant;
import com.liang.common.execption.BizCodeEnume;
import com.liang.common.utils.HttpUtils;
import com.liang.common.utils.R;
import com.liang.common.vo.MemberVo;
import com.liang.gulimall.auth.feign.MemberFeignService;
import com.liang.gulimall.auth.feign.ThirdPartFeign;
import com.liang.gulimall.auth.vo.SocialUser;
import com.liang.gulimall.auth.vo.UserLoginVo;
import com.liang.gulimall.auth.vo.UserRegisterVo;
import com.netflix.ribbon.proxy.annotation.Http;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@Slf4j
@Controller
public class LoginController {
    @Autowired
    MemberFeignService memberFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ThirdPartFeign thirdPartFeign;
    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone){
        String codeRedis = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(codeRedis)){
            long time = Long.parseLong(codeRedis.split("_")[1]);
            if (System.currentTimeMillis()-time < 60000){
                //60秒内不能在发送
                return R.error(BizCodeEnume.VAILD_SMS_CODE_EXCEPTION.getCode(),BizCodeEnume.VAILD_SMS_CODE_EXCEPTION.getMsg());
            }
        }

        String code = UUID.randomUUID().toString().substring(0, 4)+"_"+System.currentTimeMillis();//加上时间
        String smsCode=code.split("_")[0];
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,code,20, TimeUnit.SECONDS);
        thirdPartFeign.sendCode(phone, smsCode);
        return R.ok();
    }
    @PostMapping("/register")
    public String register(@Valid UserRegisterVo vo, BindingResult result, /*Model model, */RedirectAttributes redirectAttributes){
        if (result.hasErrors()){
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField,
                    FieldError::getDefaultMessage));
            //model.addAttribute("errors",errors);
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/regist.html";
        }
        String codeRedis = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (codeRedis!=null){
            String code = codeRedis.split("_")[0];//验证码
            if (vo.getCode().equals(code)){
                //删除验证码//TODO 删除验证码
                //redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                //验证码通过调用远程服务注册
                R r = memberFeignService.regist(vo);
                if (r.getCode()==0){
                    //成功
                    return "redirect:http://auth.gulimall.com/login.html";
                }else {
                    Map<String, String> errors=new HashMap<>();
                    errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.gulimall.com/regist.html";
                }

            }else {
                Map<String, String> errors=new HashMap<>();
                errors.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.gulimall.com/regist.html";
            }
        }else {
            Map<String, String> errors=new HashMap<>();
            errors.put("code","验证码失效，请重新发送");
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/regist.html";
        }
    }

    @PostMapping("/login")
    public String login(@Valid UserLoginVo vo, RedirectAttributes redirectAttributes,
                        HttpSession session){
        //远程登录
        R login = memberFeignService.login(vo);
        if (login.getCode()==0){
            MemberVo data = login.getData("data", new TypeReference<MemberVo>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_USER,data);
            return "redirect:http://gulimall.com";
        }else {
            Map<String, String> errors=new HashMap<>();
            errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }

    }

    /**
     * 微博登录
     * @param code
     * @param session
     * @return
     */
    @GetMapping("/oauth2/weibo/success")
    public String weiboLogin(@RequestParam("code") String code, HttpSession session){
        //根据code换取access_token
        Map<String,String> map=new HashMap<>();
        map.put("client_id","1680094016");
        map.put("client_secret","c81b75788660bc4189193c4a57437341");
        map.put("grant_type","authorization_code");
        map.put("code",code);
        map.put("redirect_uri","http://auth.gulimall.com/oauth2/weibo/success");
        try {
            //1、根据用户授权返回的code换取access_token
            HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), map, new HashMap<>());
            if (response.getStatusLine().getStatusCode()!=200){
                //登录失败
                return "redirect:http://auth.gulimall.com/login.html";
            }
            //处理
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSONObject.parseObject(json, SocialUser.class);
            //如果该微博用户是第一次登录，要自动注册。
            R r = memberFeignService.oauth2login(socialUser);
            if (r.getCode()==0){
                MemberVo memberVo = r.getData("data", new TypeReference<MemberVo>() {
                });
                log.info("社交登录OOK,{}",memberVo);
                //json 序列化，子域共享session
                session.setAttribute(AuthServerConstant.LOGIN_USER,memberVo);
                return "redirect:http://gulimall.com";
            }else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:http://auth.gulimall.com/login.html";
        }


    }

    /**
     * 登录后，去登录页的状态应该是跳到首页
     * @return
     */
    @GetMapping("/login.html")
    public String loginOkPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute==null){
            return "login";
        }else {
            return "redirect:http://gulimall.com";
        }

    }


}
